myApp.controller('MenuController', function ($scope, $http, $window,ngDialog,$uibModal,$state) {

    $scope.info = {};
    $scope.userRole = "";
    $scope.userName = "";
    $scope.info.userId = "";
    $scope.menus = [];

    //plan_admin 用户列表
    $scope.info.planAdminList = [];

    var rolelist_name = [];
    var rolelist_id = [];

    function createSubTree() {
        $.ajax({
            type: "GET",
            url: python_url + '/api/v1/menu/?role_id=' + JSON.stringify(rolelist_id) + '&token_id=' + getTokenId(),
            async: false,
            success: function (data) {
                $scope.menus = data.data;
            }
        });
    };

    $scope.getPlanAdminList = function () {
        $http.get(python_url + '/api/v1/user/?role_name=plan_admin&token_id=' + getTokenId(), {}).success(function (data) {
            $scope.info.planAdminList = data.data;
        });
    };

    $scope.getPlanAdminList();

    $scope.cancelPlanAdmin = function (user) {
        openDialog(ngDialog, $scope, "确定要回收"+user.realname+"的plan_admin权限么?", true, function (val) {
            if (!val) {
                return;
            }
            doBeetleGet($http, $uibModal, python_url+'/api/v1/user/delRoleForUser?role_name=plan_admin&token_id=' + getTokenId()+'&id='+user.id, function (data) {
                if (!data.success) {
                    openDialogAlert(ngDialog, $scope, data.msg);
                    return
                }
                $scope.getPlanAdminList();
            });
        });
    };

    $scope.isnull = function (url) {
        if (url == '' || url == null || url == 'null') {
            return true;
        } else {
            return false;
        }
    };

    $http.get(python_url + '/api/v1/login/info?token_id=' + getTokenId(), {}).success(function (data) {
        if (data.success == false) {
            window.location.href = "/beetle/App/module/login/tpl/login.html";
            return;
        }
        ;

        angular.forEach(data.data.role_list, function (list) {
            rolelist_name.push(list.role_name);
            rolelist_id.push(list.role_id);
        });
        setUserName(data.data.realname);
        setUserRole(rolelist_name);
        setUserId(data.data.id);
        setUserAccount(data.data.account);
        $scope.info.userId = data.data.id;
        $scope.userRole = rolelist_name;
        $scope.userName = data.data.account;
        gotoPage();
        createSubTree();
    });

    //退出登陆
    $scope.loginOut = function () {
        $http.get(python_url + '/api/v1/login/login_out?token_id=' + getTokenId()).success(function (data) {
            if (data.success == true) {
                window.location.href = "/beetle/App/module/login/tpl/login.html";
            }
        });
    };

    $scope.gotoUpdatePass = function () {
        window.location.href = "#/menu/userUpdate/" + $scope.info.userId;
    };

    function gotoPage() {
        var state = getAndRemoveStorage("to_state");
        var param = getAndRemoveStorage("to_params");
        if(state != ''){
            $state.go(state.name,param);
            return;
        }

        var userRole = getUserRole();
        var base = getContextPath();
        var url = base.substr(base.indexOf("#"), base.length);
        if (url == "#/menu") {
            if (arrayContains(userRole, 'dev') || arrayContains(userRole, 'qa') || arrayContains(userRole, 'admin')) {
                window.location.href = "#/menu/planList/";
            } else if (arrayContains(userRole, 'ops')) {
                window.location.href = "#/menu/deploy";
            } else if (userRole.length != 0) {
                window.location.href = "#/menu/planList/";
            } else {
                window.location.href = "/beetle/App/module/login/tpl/login.html";
            }
            ;
        }
        ;
    };

    // add 'ie' classes to html
    var isIE = !!navigator.userAgent.match(/MSIE/i);
    isIE && angular.element($window.document.body).addClass('ie');
    isSmartDevice($window) && angular.element($window.document.body).addClass('smart');

    // config
    $scope.app = {
        name: 'Cloudlink',
        version: '1.0.0',
        // for chart colors
        color: {
            primary: '#7266ba',
            info: '#23b7e5',
            success: '#27c24c',
            warning: '#fad733',
            danger: '#f05050',
            light: '#e8eff0',
            dark: '#3a3f51',
            black: '#1c2b36'
        },
        settings: {}
    };

    $scope.lang = {isopen: false};
    $scope.langs = {zh: 'china', en: 'English'};

    function isSmartDevice($window) {
        // Adapted from http://www.detectmobilebrowsers.com
        var ua = $window['navigator']['userAgent'] || $window['navigator']['vendor'] || $window['opera'];
        // Checks for iOs, Android, Blackberry, Opera Mini, and Windows mobile devices
        return (/iPhone|iPod|iPad|Silk|Android|BlackBerry|Opera Mini|IEMobile/).test(ua);
    }

    $scope.assignRole = function () {
        var info = {};
        var modalInstance = $uibModal.open({
            animation: true,
            templateUrl: 'assignRole.html',
            controller: 'AssignRoleCtrl',
            resolve: {
                info: function () {
                    return info;
                }
            }
        });
        modalInstance.result.then(function (result) {},
            function (reason) {
                if(reason == 'save'){
                    $scope.getPlanAdminList();
                }
            });
    };
});
myApp.controller('AssignRoleCtrl', function ($scope, $uibModal, $uibModalInstance, info, $http, ngDialog) {
    $scope.info = info;
    $scope.info.userInfo = {};
    $scope.info.list = [];

    doBeetleGet($http,$uibModal,python_url + '/api/v1/user/?token_id=' + getTokenId(),function (data) {
        $scope.info.list = data.data;
        $scope.info.userInfo =$scope.info.list[0];
    });

    $scope.save = function () {
        openDialog(ngDialog, $scope, "确定要将用户"+$scope.info.userInfo.realname+"设置为plan_admin吗？", true, function (val) {
            if (!val) {
                return;
            }
            doBeetleGet($http, $uibModal, python_url+'/api/v1/user/addRoleForUser?role_name=plan_admin&token_id=' + getTokenId()+'&id='+$scope.info.userInfo.id, function (data) {
                if (data.success) {
                    $uibModalInstance.dismiss('save');
                } else {
                    openDialogAlert(ngDialog,$scope,data.msg);
                }
            });
        })
    };
    $scope.cancel = function () {
        $uibModalInstance.close('cancel');
    };
});